<template>
    <div class="icon-manager">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <h2>图标管理</h2>
            <el-tag type="info">共 {{ total }} 个图标</el-tag>
        </div>

        <div class="content-box">
            <!-- 操作栏 -->
            <el-card class="operation-area" shadow="hover">
                <!-- 搜索区域 -->
                <el-form ref="searchFormRef" :inline="true" :model="listQuery" class="search-form">
                    <el-form-item label="图标名称">
                        <el-input v-model="listQuery.itemKey" placeholder="请输入图标名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" plain @click="onSubmit">
                            <el-icon><Search /></el-icon> 查询
                        </el-button>
                        <el-button plain @click="onReset">
                            <el-icon><Refresh /></el-icon> 重置
                        </el-button>
                    </el-form-item>
                </el-form>

                <!-- 按钮区域 -->
                <div class="control-btns">
                    <el-button type="danger" plain size="default" @click="batchDelete" :disabled="!multipleSelection.length">
                        <el-icon><Delete /></el-icon> 批量删除
                    </el-button>
                    <div class="right-btns">
                        <el-button type="primary" plain size="default" @click="exportVisible = true">
                            <el-icon><Download /></el-icon> 导出数据
                        </el-button>
                        <el-button type="primary" plain size="default" @click="handleCreate">
                            <el-icon><Plus /></el-icon> 新增图标
                        </el-button>
                    </div>
                </div>
            </el-card>

            <!-- 表格区域 -->
            <el-card class="table-card" shadow="hover">
                <el-table ref="multipleTableRef"
                         v-loading="listLoading" 
                         :data="tableData" 
                         tooltip-effect="dark" 
                         row-key="id"
                         style="width: 100%" 
                         size="default"
                         @selection-change="handleSelectionChange"
                         border>
                    <el-table-column type="selection" width="50" align="center"></el-table-column>
                    <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
                    <el-table-column prop="itemKey" label="图标名称" min-width="120"></el-table-column>
                    <el-table-column prop="itemValue" label="图标值" min-width="120"></el-table-column>
                    <el-table-column label="图标预览" width="100" align="center">
                        <template #default="scope">
                            <i :class="scope.row.itemValue" style="font-size: 20px;"></i>
                        </template>
                    </el-table-column>
                    <el-table-column prop="description" label="描述" min-width="150"></el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="160" align="center"></el-table-column>
                    <el-table-column prop="updateTime" label="更新时间" width="160" align="center"></el-table-column>
                    <el-table-column label="操作" width="180" align="center" fixed="right">
                        <template #default="scope">
                            <el-button size="small" type="primary" plain @click="handleEdit(scope.row)">
                                <el-icon><Edit /></el-icon> 编辑
                            </el-button>
                            <el-button size="small" type="danger" plain @click="handleDelete(scope.row.id)">
                                <el-icon><Delete /></el-icon> 删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <pagination v-show="total > 0" 
                          :total="total" 
                          v-model:page="listQuery.currentPage"
                          v-model:limit="listQuery.pageSize"
                          @pagination="fetchData" />
            </el-card>

            <!-- 新增/编辑弹窗 -->
            <el-dialog :title="dialogForm.id ? '编辑图标' : '新增图标'" 
                      v-model="formVisible"
                      width="500px"
                      :close-on-click-modal="false">
                <el-form :model="dialogForm" :rules="formRules" ref="dialogFormRef" label-width="100px">
                    <el-form-item label="图标名称" prop="itemKey">
                        <el-input v-model="dialogForm.itemKey" placeholder="请输入图标名称"></el-input>
                    </el-form-item>
                    <el-form-item label="图标值" prop="itemValue">
                        <el-input v-model="dialogForm.itemValue" placeholder="请输入图标值">
                            <template #append>
                                <i :class="dialogForm.itemValue" style="font-size: 18px;"></i>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="描述">
                        <el-input type="textarea" v-model="dialogForm.description" placeholder="请输入描述信息"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="formVisible = false" plain>取 消</el-button>
                        <el-button type="primary" :loading="isSubmit" @click="handleSave" plain>确 定</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 导出数据弹窗 -->
            <el-dialog title="导出数据" v-model="exportVisible" width="400px" :close-on-click-modal="false">
                <div class="export-data">
                    <el-button type="primary" plain @click="exportTable('xlsx')">
                        <el-icon><Document /></el-icon> EXCEL格式
                    </el-button>
                    <el-button type="primary" plain @click="exportTable('csv')">
                        <el-icon><Document /></el-icon> CSV格式
                    </el-button>
                    <el-button type="primary" plain @click="exportTable('txt')">
                        <el-icon><Document /></el-icon> TXT格式
                    </el-button>
                </div>
                <div class="hints">提示：请选择要导出数据的格式</div>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElCard, ElForm, ElFormItem, ElInput, ElButton, ElTable, ElTableColumn, ElDialog, ElIcon, ElTag } from 'element-plus'
import { Search, Refresh, Delete, Download, Plus, Edit, Document } from '@element-plus/icons-vue'
import excel from '../utils/excel.js'
import Pagination from '../components/Pagination/index.vue'
import Request from '../utils/request.js'

// 表单引用
const searchFormRef = ref()
const multipleTableRef = ref()
const dialogFormRef = ref()

// 响应式数据
const listLoading = ref(true)
const formLabelWidth = ref('80px')
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const formVisible = ref(false)
const isSubmit = ref(false)
const exportVisible = ref(false)

// 查询列表参数对象
const listQuery = reactive({
    itemKey: undefined,
    currentPage: 1,
    pageSize: 10
})

// 新增/编辑提交表单对象
const dialogForm = reactive({
    id: undefined, // 需要有id字段以区分新增和编辑
    dictTypeCode: 'icon', // 字典类型Code，这里假设是固定的
    itemKey: '',
    itemValue: '',
    description: '',
})

// 表单校验规则
const formRules = reactive({
    itemKey: [
        { required: true, message: '字典键不能为空', trigger: 'blur' },
        { min: 1, max: 20, message: '字典键长度必须在1到20个字符之间', trigger: 'blur' }
    ],
    itemValue: [
        { required: true, message: '字典值不能为空', trigger: 'blur' },
        { min: 1, max: 50, message: '字典值长度必须在1到50个字符之间', trigger: 'blur' }
    ],
    description: [
        { max: 100, message: '描述内容不能超过100个字符', trigger: 'blur' }
    ],
})

// 多选操作
const handleSelectionChange = (val) => {
    multipleSelection.value = val.map(v => v.id);
    console.log('选中的数据:', multipleSelection.value);
}

// 新建数据
const handleCreate = () => {
    Object.assign(dialogForm, {
        dictTypeCode: 'icon',
        itemKey: '',
        itemValue: '',
        description: ''
    })
    formVisible.value = true
}

// 编辑数据
const handleEdit = (row) => {
    Object.assign(dialogForm, JSON.parse(JSON.stringify(row)))
    formVisible.value = true
}

// 删除数据
const handleDelete = (id) => {
    ElMessageBox.confirm('确认删除该图标?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await Request.delete(`/dictitem/deleteById/${id}`);
            if (res.code === '0') {
                ElMessage.success('删除成功');
                fetchData();
            } else {
                ElMessage.error(res.msg || '删除失败');
            }
        } catch (error) {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 批量删除
const batchDelete = () => {
    if (!multipleSelection.value.length) {
        ElMessage.warning('请先选择要删除的数据！');
        return;
    }

    ElMessageBox.confirm('确认删除选中的图标?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const ids = multipleSelection.value.join(',');
            const res = await Request.delete(`/dictitem/deleteBatch?idList=${ids}`);
            if (res.code === '0') {
                ElMessage.success('批量删除成功');
                fetchData();
            } else {
                ElMessage.error(res.msg || '批量删除失败');
            }
        } catch (error) {
            console.error('批量删除失败:', error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 获取数据列表
const fetchData = async () => {
    listLoading.value = true;
    try {
        const res = await Request.get("/dictitem/findPage", {
            params: {
                code: "icon",
                itemKey: listQuery.itemKey,
                currentPage: listQuery.currentPage,
                size: listQuery.pageSize,
            }
        });

        if (res.code === '0') {
            total.value = res.data.total;
            tableData.value = res.data.records;
            // 清空选择
            multipleSelection.value = [];
            if (multipleTableRef.value) {
                multipleTableRef.value.clearSelection();
            }
        }
    } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取数据失败');
    } finally {
        listLoading.value = false;
    }
}

// 查询数据
const onSubmit = () => {
    listQuery.currentPage = 1
    fetchData()
}

const onReset = () => {
    listQuery.currentPage = 1
    listQuery.pageSize = 10;
    listQuery.itemKey = "";
    fetchData()
}

const handleSave = () => {
    dialogFormRef.value.validate(async valid => {
        if (!valid) {
            console.log('表单验证失败!')
            return false
        }

        isSubmit.value = true
        try {
            // 创建一个新对象，只包含需要的字段
            const submitData = {
                dictTypeCode: dialogForm.dictTypeCode,
                itemKey: dialogForm.itemKey,
                itemValue: dialogForm.itemValue,
                description: dialogForm.description
            }

            // 如果是编辑，添加 id
            if (dialogForm.id) {
                submitData.id = dialogForm.id
            }

            const method = submitData.id ? 'put' : 'post'
            const url = submitData.id
                ? `/dictitem/${submitData.id}`
                : '/dictitem/save'

            const response = await Request[method](url, submitData)

            if (response.code === '0') {
                ElMessage.success(submitData.id ? '更新成功' : '添加成功')
                formVisible.value = false
                fetchData()
            } else {
                ElMessage.error(response.msg || (submitData.id ? '更新失败' : '添加失败'))
            }
        } catch (error) {
            console.error('保存失败:', error)
            ElMessage.error('操作失败')
        } finally {
            isSubmit.value = false
        }
    })
}

// 导出数据
const exportTable = (type) => {
    if (tableData.value.length) {
        const params = {
            header: ['ID', '图标名称', '图标值', '描述', '创建时间', '更新时间'],
            key: ['id', 'itemKey', 'itemValue', 'description', 'createTime', 'updateTime'],
            data: tableData.value,
            autoWidth: true,
            fileName: '图标数据表',
            bookType: type
        }
        excel.exportDataToExcel(params)
        exportVisible.value = false
    }
}

// 生命周期钩子
onMounted(() => {
    fetchData()
})
</script>

<style lang="less" scoped>
.icon-manager {
    padding: 24px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
}

.page-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;

    h2 {
        font-size: 24px;
        font-weight: 500;
        color: #1f2f3d;
        margin: 0;
        margin-right: 15px;
    }
}

.operation-area {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
}

.search-form {
    margin-bottom: 20px;
    padding: 20px 20px 0;
    border-radius: 4px;
}

.table-card {
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.control-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px 20px;

    .right-btns {
        display: flex;
        gap: 10px;
    }
}

:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: none;

    th {
        background-color: #fafafa;
        font-weight: 500;
        color: #1f2f3d;
        padding: 12px 0;
    }

    td {
        padding: 12px 0;
    }
}

:deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    .el-dialog__header {
        padding: 24px;
        border-bottom: 1px solid #ebeef5;
        margin: 0;
    }

    .el-dialog__title {
        font-size: 18px;
        font-weight: 500;
        color: #1f2f3d;
    }

    .el-dialog__body {
        padding: 32px 24px;
    }

    .el-dialog__footer {
        padding: 16px 24px;
        border-top: 1px solid #ebeef5;
    }
}

.export-data {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
}

.hints {
    text-align: center;
    color: #909399;
    font-size: 12px;
}
</style>